/* 2014/4/2 */
package com.cosmos.mail.sender;

import java.util.Properties;

import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.internet.MimeMessage;

import com.cosmos.mail.entity.MailEntity;


/**
 * Sends mail directly, without adding record to DB.
 * This sender makes sure mails can be sent even if "SendMail" agent cannot work.
 * @author Leonardo
 *
 */
public class DirectSender implements MailSender {

	private class SimpleAuthenticator extends Authenticator {
		private PasswordAuthentication passwordAuthentication;
		
		public SimpleAuthenticator(String username, String password) {
			passwordAuthentication = new PasswordAuthentication(username, password);
		}
		
		@Override
		protected PasswordAuthentication getPasswordAuthentication() {
			return passwordAuthentication;
		}		
	}
	
	public static final String CONTENT_TYPE_HTML = "text/html;charset=UTF-8";
	public static final String CONTENT_TYPE_TXT = "text/plain;charset=UTF-8";
	
	private Session devSession;
	private String defaultFromAddress;
	
	/**
	 * @see com.cosmos.mail.sender.MailSender#init()
	 */
	public void init(Object... args) {
		devSession = getDevSession();
		defaultFromAddress = "";
	}

	/**
	 * @see com.cosmos.mail.sender.MailSender#destroy()
	 */
	public void destroy() {

	}
	
	/**
	 * @see com.cosmos.mail.sender.MailSender#send(com.cosmos.mail.entity.MailEntity)
	 */
	public void send(MailEntity entity) {
		
	}
	
	private Message getMessage(MailEntity mail, String contentType) {
		Message message = new MimeMessage(getDevSession());
		
		return message;
	}
	
	private Session getDevSession() {
		String username = getConfigureUserName();
		String password = getConfigurePassword();
		String smtpHost = getConfigureSmtpHost();
		
		Properties properties = new Properties();
		Authenticator authenticator = null;
		if((null != username && !"".equals(username)) && (null != password && !"".equals(password))) {
			properties.setProperty("mail.smtp.auth", "true");
			authenticator = new SimpleAuthenticator(username, password);
		}
		if(smtpHost != null) {
			properties.setProperty("mail.smtp.host", smtpHost);
		} else {
			properties.setProperty("mail.smtp.host", "d23m0016.cn.ibm.com");
		}
		properties.setProperty("mail.transport.protocol", "smtp");
		// Avoid hang by setting timeout; 60 seconds
		properties.setProperty("mail.smtp.timeout", "60000");
		properties.setProperty("mail.smtp.connectiontimeout", "60000");
		
		if (authenticator != null) {
			return Session.getInstance(properties, authenticator);
		} else {
			return Session.getInstance(properties);
		}
	}
	
	private String getConfigureUserName() {
		return "";
	}
	
	private String getConfigurePassword() {
		return "";
	}
	
	private String getConfigureSmtpHost() {
		return "";
	}
}
